<template>
  <div>
    <!-- 拖拽开关的开启与关闭 -->
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    ></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      show-checkbox
      node-key="catId"
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            edit
          </el-button>
        </span>
      </span>
    </el-tree>

    <!-- 添加菜單对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subminData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      title: "",
      dialogType: "",
      menus: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      expandedKey: [],
      dialogVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catelevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        productCount: 0,
        productUnit: "",
        icon: "",
      },
      maxLevel: 1,
      updateNodes: [],
    };
  },
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        this.menus = data.page;
      });
    },
    append(data) {
      console.log(data);
      this.dialogVisible = true;
      this.category.parentCid = data.catId;

      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.catelevel = data.catLevel * 1 + 1;
      this.dialogType = "add";
      this.title = "添加菜单";
    },
    addCategory() {
      console.log("表单数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "菜单添加成功",
            type: "success",
          });
          // 刷新菜单数据
          this.getMenus();
          // 展开点击的数据节点
          this.expandedKey = [this.category.parentCid];
          // 关闭对话框
          this.dialogVisible = false;
        }
      });
    },
    remove(node, data) {
      var ids = [data.catId];
      this.$confirm(`确认删除[${data.name}]菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getMenus();
              this.expandedKey = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    edit(data) {
      this.dialogVisible = true;
      this.dialogType = "exid";
      this.title = "修改菜单";
      // 获取最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        //請求成功
        console.log(data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },
    editProduct() {
      var { catId, name, icon, productUnit } = this.category;
      console.log({
        catId,
        name,
        icon,
        productUnit,
      });
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(
          {
            catId,
            name,
            icon,
            productUnit,
          },
          false
        ),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "菜单修改成功",
            type: "success",
          });
          // 刷新菜单数据
          this.getMenus();
          // 展开点击的数据节点
          this.expandedKey = [this.category.parentCid];
          // 关闭对话框
          this.dialogVisible = false;
        }
      });
    },
    subminData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "exid") {
        this.editProduct();
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      /*
         逻辑结构：
          进行拖拽 获取选中的菜单的数据  A，
            通过获取A的数值最大的级别 也就是获取A共有多少子菜单
              将A的子菜单与要添加的菜单的级别相减在加一 获取到当前菜单的新级别deep
                通过类型判断是否是同级移动
                  true ： 就只需判断与当前级别相加后是否大于三
                  false：判断与父结点相加后 是否大约3
        */
      this.countNodeLevel(draggingNode);
      console.log(draggingNode);
      console.log(draggingNode.data.catLevel);
      let deep = Math.abs(this.maxLevel - draggingNode.level + 1);
      console.log("深度：" + deep);
      console.log(type);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    batchSave() {
      // 修改成功进行提交
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单顺序修改成功",
          type: "success",
        });
        // 刷新菜单
        this.getMenus();
        // 打开拖拽的父id
        this.expandedKey = [this.pCid];
        // 清空操作
        this.updateNodes = [];
        this.maxLevel = 0;
        // this.pCid = 0;
      });
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("handleDrop: ", draggingNode, dropNode, dropType);
      // 当前节点最新父id
      let pCid = 0;
      // 当节点最新的兄弟节点
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);
      // 将数据进行排序
      for (let i = 0; i < siblings.length; i++) {
        // 遍历正在有拖拽的节点 要改变其父节点
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.level;
          // 如果正在拖拽的节点发生层级变化 改变层级信息
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            // 修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      console.log(this.updateNodes);
    },
    // 递归操作
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    batchDelete(){
       const element=[]
      let checkedNodes=  this.$refs.menuTree.getCheckedNodes();
      console.log(checkedNodes)
      for (let i = 0; i < checkedNodes.length; i++) {
       element.push(checkedNodes[i].catId);
      }
       this.$confirm(`确认删除[${element}]菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(()=>{
         this.$http({
        url:this.$http.adornUrl("/product/category/delete"),
        method:"post",
        data:this.$http.adornData(element,false)
        }).then(({data})=>{
          this.$message({
            message:"菜单批量删除成功"
          })
          this.getMenus();
          
        })

      }).catch(()=>{})
      
    },
    
  },
  created() {
    this.getMenus();
  },
};
</script>

<style>
</style>
